package main

import (
	"bufio"
	"encoding/json"
	"fmt"
	"go-regx/cmd"
	"go-regx/matcher"
	"log"
	"os"
)

var (
	Case_map  = make(map[string][]*TestCase)
	Case_list []*TestCase
)

func runTest(m *matcher.Matcher) {
	file_list, err := m.readDirectory(cmd.Conf_arg.Test)
	if err != nil {
		log.Fatalf("读取测试目录失败: %v", err)
	}

	for _, i := range file_list {
		var tlist []*matcher.TestCase
		file, err := os.Open(i)
		if err != nil {
			log.Fatalf("文件%s打开失败: %v", i, err)
		}
		defer file.Close()

		scanner := bufio.NewScanner(file)
		for scanner.Scan() {
			line := scanner.Text()
			var tc matcher.TestCase
			err := json.Unmarshal([]byte(line), &tc)
			if err != nil {
				log.Printf("Error %s parsing JSON: %v\n", line, err)
				continue
			}
			m.Case_list = append(m.Case_list, &tc)
			tlist = append(tlist, &tc)
		}

		if err := scanner.Err(); err != nil {
			log.Fatalf("scanner读取输入错误: %v", err)
		}
		matcher.Case_map[i] = tlist
		if cmd.Conf_arg.Verbose {
			for i, j := range m.Case_list {
				log.Printf("test %d: value:%v", i, j)
			}
		}

		match_result := m.ProcessText()

		if cmd.Conf_arg.Verbose {
			for i, j := range match_result {
				fmt.Println(i, " : ", j, j.Etime.Nanoseconds(), "ns")
			}
		}
		jsonData, err := json.Marshal(match_result)
		if err != nil {
			log.Print("Error marshal to JSON:", err)
			return
		}
		fmt.Println("------测试匹配结果------")
		fmt.Println(string(jsonData))
		fmt.Println("------测试结果输出------")

		for k, v := range matcher.Case_map {
			number := 0
			for i, j := range v {
				ismatch := 0
				notmatch := 0
				for _, m := range j.Spans {
					if m.Priority > 0 {
						ismatch++
					} else {
						notmatch++
						fmt.Println("FAIL:", k, i+1, "line", m.Label, m.Start, m.End, m.Rstart, m.Rend)
					}
				}
				if len(j.Spans) == ismatch {
					number++
				}
			}

			fail_number := len(v) - number
			str_head := ""
			if fail_number != 0 {
				str_head = "\033[31m"
			}
			fmt.Println("测试用例：", k, str_head+"测试用例数：", len(v), "\t成功：", number, "\t失败：", fail_number, "\033[0m")
		}
	}
}

func main() {
	rulePath := "path/to/rules" // 假设规则路径
	m := matcher.NewMatcher()
	err := m.LoadRules(rulePath)
	if err != nil {
		log.Fatalf("加载规则失败: %v", err)
	}
	defer m.Close()

	runTest(m)
}
